package com.demo.chapter1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.groupingBy;
import com.demo.domain.Transaction;

public class TransactionGroupBy {
	
	//老代码：先取出交易金额大于1000的，然后按币种分类保存
	private Map<String, List<Transaction>> demo(List<Transaction> transactions){
		Map<String, List<Transaction>> transactionsByCurrencies = new HashMap<String, List<Transaction>>();
		
		for(Transaction transaction: transactions){
			if(transaction.getPrice() > 1000){
				String currency = transaction.getCurrency();
				List<Transaction> transactionsByCurrency = transactionsByCurrencies.get(currency);
				if(transactionsByCurrency == null){
					transactionsByCurrency = new ArrayList<Transaction>();
					transactionsByCurrencies.put(currency, transactionsByCurrency);
				}
				transactionsByCurrency.add(transaction);
			}
		}
		
		return transactionsByCurrencies;
	}
	
	//新代码
	private Map<String, List<Transaction>> demo2(List<Transaction> transactions){
		return transactions.stream().filter((Transaction transaction) -> transaction.getPrice() > 1000).collect(groupingBy(Transaction::getCurrency));
	}

}
